package com.example.demo.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.example.demo.ao.CreateMeetingAo;
import com.example.demo.ao.InsertMeetingMinutesAo;
import com.example.demo.ao.MeetingMinutesAo;
import com.example.demo.service.MeetingMinutesService;
import com.example.demo.vo.MeetingMinutesVo;
import com.example.demo.vo.MeetingRoomVo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/meeting")
@Slf4j
public class MeetingMinutesController {


    @Autowired
    private MeetingMinutesService meetingMinutesService;


    @PostMapping("/search")
    public Page<MeetingMinutesVo> getMeetingMinutes(@RequestBody MeetingMinutesAo meetingMinutesAo) {
        return meetingMinutesService.getMeetingMinutes(meetingMinutesAo);
    }


    @PostMapping("/info")
    public List<MeetingMinutesVo> getMeetingMinutesInfo(@RequestBody MeetingMinutesAo meetingMinutesAo) {
        return meetingMinutesService.getMeetingMinutesInfo(meetingMinutesAo);
    }


    @PostMapping("/insert")
    public String insertMeetingMinutes(@RequestBody InsertMeetingMinutesAo insertMeetingMinutesAo, HttpServletRequest request) {
        return meetingMinutesService.insertMeetingMinutes(insertMeetingMinutesAo, request);
    }


    @PostMapping("/update")
    public String updateMeetingMinutes(@RequestBody InsertMeetingMinutesAo insertMeetingMinutesAo, HttpServletRequest request) {
        return meetingMinutesService.updateMeetingMinutes(insertMeetingMinutesAo, request);
    }


    @GetMapping("/export")
    public void exportTemplate(HttpServletResponse response) throws IOException {
        String fileName = URLEncoder.encode("营销会议模板_" + System.currentTimeMillis(), "UTF-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        ExcelWriter writer = ExcelUtil.getWriter(true);
        try {
            writer.renameSheet("日例会");
            createDailyMeetingSheet(writer);

            writer.setSheet("专题会");
            createSpecialMeetingSheet(writer);

            writer.setSheet("其他会议");
            createOtherMeetingSheet(writer);

            writer.flush(response.getOutputStream(), true);
        } finally {
            writer.close();
        }
    }


    private void createDailyMeetingSheet(ExcelWriter writer) {
        // 设置表头
        List<String> headers = Arrays.asList(
                "序号", "会议时间", "会议地点", "会议主题",
                "涉及业务组", "主持人", "参会人员", "会议内容", "备注"
        );

        writer.writeHeadRow(headers);

        // 添加示例数据
        List<Object> row1 = Arrays.asList(
                1,
                LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")),
                "3401会议室",
                "日例会",
                "各个产品线",
                "XXX",
                "各个组长",
                "XXXX年XX月XX日会议内容",
                ""
        );

        writer.writeRow(row1);

        // 设置列宽
        writer.setColumnWidth(0, 8);   // 序号
        writer.setColumnWidth(1, 20);  // 会议时间
        writer.setColumnWidth(2, 15);  // 会议地点
        writer.setColumnWidth(3, 15);  // 会议主题
        writer.setColumnWidth(4, 15);  // 涉及业务组
        writer.setColumnWidth(5, 10);  // 主持人
        writer.setColumnWidth(6, 20);  // 参会人员
        writer.setColumnWidth(7, 40);  // 会议内容
        writer.setColumnWidth(8, 15);  // 备注
    }



    private void createSpecialMeetingSheet(ExcelWriter writer) {
        // 设置表头
        List<String> headers = Arrays.asList(
                "序号", "会议日期", "会议时间", "会议地点", "会议主题",
                "涉及业务组", "主持人", "参会人员", "会议内容", "解决问题", "遗留任务"
        );

        writer.writeHeadRow(headers);

        // 添加示例数据
        List<Object> row1 = Arrays.asList(
                1,
                LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")),
                "10:30",
                "3401会议室",
                "专题会",
                "各个产品线",
                "XXX",
                "各个组长",
                "XXXX年XX月XX日会议内容",
                "",
                ""
        );

        writer.writeRow(row1);

        writer.setColumnWidth(0, 8);   // 序号
        writer.setColumnWidth(1, 15);  // 会议日期
        writer.setColumnWidth(2, 12);  // 会议时间
        writer.setColumnWidth(3, 15);  // 会议地点
        writer.setColumnWidth(4, 20);  // 会议主题
        writer.setColumnWidth(5, 20);  // 涉及业务组
        writer.setColumnWidth(6, 10);  // 主持人
        writer.setColumnWidth(7, 25);  // 参会人员
        writer.setColumnWidth(8, 40);  // 会议内容
        writer.setColumnWidth(9, 20);  // 解决问题
        writer.setColumnWidth(10, 20); // 遗留任务

    }


    private void createOtherMeetingSheet(ExcelWriter writer) {
        // 设置表头
        List<String> headers = Arrays.asList(
                "序号", "会议日期", "会议时间", "会议地点", "会议主题",
                "涉及业务组", "主持人", "参会人员", "会议内容", "解决问题", "遗留任务"
        );

        writer.writeHeadRow(headers);

        // 添加示例数据
        List<Object> row1 = Arrays.asList(
                1,
                LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")),
                "10:30",
                "3401会议室",
                "专题会",
                "各个产品线",
                "XXX",
                "各个组长",
                "XXXX年XX月XX日会议内容",
                "",
                ""
        );

        writer.writeRow(row1);

        writer.setColumnWidth(0, 8);   // 序号
        writer.setColumnWidth(1, 15);  // 会议日期
        writer.setColumnWidth(2, 12);  // 会议时间
        writer.setColumnWidth(3, 15);  // 会议地点
        writer.setColumnWidth(4, 20);  // 会议主题
        writer.setColumnWidth(5, 25);  // 涉及业务组
        writer.setColumnWidth(6, 10);  // 主持人
        writer.setColumnWidth(7, 25);  // 参会人员
        writer.setColumnWidth(8, 40);  // 会议内容
        writer.setColumnWidth(9, 20);  // 解决问题
        writer.setColumnWidth(10, 20); // 遗留任务

    }


    @PostMapping("/upload/excel")
    public String upLoadTxtFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()) {
            return "文件为空,请重新上传";
        }
        SimpleDateFormat outputFormatter = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat datetimeFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            //获取所有sheet
            List<String> sheets = reader.getSheetNames();
            for (String sheet : sheets) {
                reader.setSheet(sheet);
                if ("日例会".equals(sheet)) {
                    handleSheet1(reader, request, outputFormatter);
                } else if ("专题会".equals(sheet) || "其他会议".equals(sheet)) {
                    handleSheet2And3(reader, request, datetimeFormatter); // 移除了sheet参数
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败：" + e.getMessage();
        }
        return "插入成功";
    }


    //解析日期
    private Date parseFlexibleDate(String dateStr) {
        if (dateStr == null || dateStr.isEmpty()) return null;

        String[] datePatterns = {
                "yyyy年MM月dd日", "yyyy年M月d日", "yyyy年M月dd日", "yyyy年MM月d日",
                "yyyy/MM/dd", "yyyy/M/d", "yyyy/MM/d", "yyyy/M/dd",
                "yyyy-MM-dd", "yyyy-M-d", "yyyy-MM-d", "yyyy-M-dd"
        };

        for (String pattern : datePatterns) {
            try {
                return new SimpleDateFormat(pattern).parse(dateStr);
            } catch (ParseException ignored) {
            }
        }
        return null;
    }

    // 解析时间
    private Date parseFlexibleTime(String timeStr) {
        if (timeStr == null || timeStr.isEmpty()) return null;

        String[] timePatterns = {"HH:mm", "H:mm", "HH:m", "H:m", "HH:mm:s", "HH:mm:ss"};

        for (String pattern : timePatterns) {
            try {
                return new SimpleDateFormat(pattern).parse(timeStr);
            } catch (ParseException ignored) {
            }
        }
        return null;
    }


    private void handleSheet1(ExcelReader reader, HttpServletRequest request, SimpleDateFormat outputFormatter) {
        reader.addHeaderAlias("会议时间", "meetingTime");
        reader.addHeaderAlias("会议地点", "meetingRoom");
        reader.addHeaderAlias("会议主题", "topic");
        reader.addHeaderAlias("涉及业务组", "meetingGroup");
        reader.addHeaderAlias("主持人", "speaker");
        reader.addHeaderAlias("参会人员", "meetingPerson");
        reader.addHeaderAlias("会议内容", "minutesContent");
        reader.addHeaderAlias("解决问题", "killQues");
        reader.addHeaderAlias("遗留任务", "legacyMissions");

        List<InsertMeetingMinutesAo> tests = reader.readAll(InsertMeetingMinutesAo.class);

        for (InsertMeetingMinutesAo test : tests) {
            if (test.getMeetingTime() == null || test.getMeetingTime().isEmpty()) {
                System.out.println("会议时间为空，不处理时间字段，插入其他数据");
                meetingMinutesService.insertMeetingMinutes(test, request);
                continue;
            }

            Date date = parseFlexibleDate(test.getMeetingTime());
            if (date != null) {
                test.setMeetingTime(outputFormatter.format(date));
            } else {
                System.out.println("日期格式无法识别: " + test.getMeetingTime());
                test.setMeetingTime("");
            }

            meetingMinutesService.insertMeetingMinutes(test, request);
        }
    }

    private void handleSheet2And3(ExcelReader reader, HttpServletRequest request, SimpleDateFormat datetimeFormatter) {
        reader.addHeaderAlias("会议日期", "meetingDate");
        reader.addHeaderAlias("会议时间", "meetingTimePart");
        reader.addHeaderAlias("会议地点", "meetingRoom");
        reader.addHeaderAlias("会议主题", "topic");
        reader.addHeaderAlias("涉及业务组", "meetingGroup");
        reader.addHeaderAlias("主持人", "speaker");
        reader.addHeaderAlias("参会人员", "meetingPerson");
        reader.addHeaderAlias("会议内容", "minutesContent");
        reader.addHeaderAlias("解决问题", "killQues");
        reader.addHeaderAlias("遗留任务", "legacyMissions");

        List<InsertMeetingMinutesAo> tests = reader.readAll(InsertMeetingMinutesAo.class);

        for (InsertMeetingMinutesAo test : tests) {
            if (test.getMeetingDate() == null || test.getMeetingDate().isEmpty() || test.getMeetingTimePart() == null || test.getMeetingTimePart().isEmpty()) {
                System.out.println("会议时间为空，不处理时间字段，插入其他数据");
                meetingMinutesService.insertMeetingMinutes(test, request);
                continue;
            }
            //  解析日期
            Date datePart = parseFlexibleDate(test.getMeetingDate());
            if (datePart == null) {
                System.out.println("会议日期格式无法识别: " + test.getMeetingDate());
                continue;
            }

            // 处理时间
            Date timePart = null;
            if (test.getMeetingTimePart() != null && !test.getMeetingTimePart().isEmpty()) {
                timePart = parseFlexibleTime(test.getMeetingTimePart());
                System.out.println("这里是时间测试" + timePart);
            }

            // 组合日期和时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(datePart);

            if (timePart != null) {
                Calendar timeCalendar = Calendar.getInstance();
                timeCalendar.setTime(timePart);
                calendar.set(Calendar.HOUR_OF_DAY, timeCalendar.get(Calendar.HOUR_OF_DAY));
                calendar.set(Calendar.MINUTE, timeCalendar.get(Calendar.MINUTE));
            } else {
                // 没有时间部分时使用默认时间
                calendar.set(Calendar.HOUR_OF_DAY, 12);
                calendar.set(Calendar.MINUTE, 0);
                System.out.println("使用默认时间");
            }

            // 格式化为最终需要的日期格式
            test.setMeetingTime(datetimeFormatter.format(calendar.getTime()));
            meetingMinutesService.insertMeetingMinutes(test, request);
        }

    }




    //会议室
    @PostMapping("/room")
    public List<MeetingRoomVo> getMeetingRoom() {
        return meetingMinutesService.getMeetingRoom();
    }


    @PostMapping("/room/insert")
    public String insertMeetingRoom(@RequestBody CreateMeetingAo createMeetingAo, HttpServletRequest request) {
        String result = "";
        result = meetingMinutesService.insertMeetingRoom(createMeetingAo, request);
        if ("success".equals(result)) {
            return result;
        }else {
            return null;
        }
    }


    @PostMapping("/room/info")
    public List<MeetingRoomVo> getMeetingRoomInfo(@RequestBody CreateMeetingAo createMeetingAo) {
        return meetingMinutesService.getMeetingRoomInfo(createMeetingAo);
    }


    @PostMapping("/application")
    public String insertMeetingApplication(@RequestBody CreateMeetingAo createMeetingAo, HttpServletRequest request) {
        String result = "";
        result = meetingMinutesService.insertMeetingApplication(createMeetingAo, request);
        if ("success".equals(result)) {
            return result;
        }else {
            return null;
        }
    }

    @PostMapping("/user/info")
    public Page<MeetingRoomVo> getUserRoomInfo(@RequestBody CreateMeetingAo createMeetingAo, HttpServletRequest request) {
        return meetingMinutesService.getUserRoomInfo(createMeetingAo, request);
    }


    @PostMapping("/analyse")
    public Page<MeetingRoomVo> getUserRoomInfo(@RequestBody CreateMeetingAo createMeetingAo) {
        return meetingMinutesService.getRoomAnalyse(createMeetingAo);
    }
}
